<template>
  <div class="app-container">
    <el-row v-if="isExecute&&!bomId" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:wm:outsourceissue:execute']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="outsourceissuelineList" @selection-change="handleSelectionChange">
      <el-table-column label="产品物料编码" width="120px" align="center" prop="itemCode" />
      <el-table-column label="产品物料名称" width="120px"  align="center" prop="itemName" :show-overflow-tooltip="true"/>
      <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true"/>
      <el-table-column label="批次号" align="center" prop="batchCode" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="库区名称" align="center" prop="locationName" />
      <el-table-column label="库位名称" align="center" prop="areaName" />

      <el-table-column
        v-for="col in columnsConfig"
        :key="col.prop"
        :label="col.label"
        :prop="col.prop"
        :width="col.width"
        :align="col.align"
        v-if="col.show">
      </el-table-column>
      <el-table-column label="单位（主）" align="center" prop="unitOfMeasure" fixed="right"/>
      <el-table-column label="领料数量（主）" align="center" prop="quantityIssued" width="120" fixed="right">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.updateStatus"
            size="mini"
            style="width: 100px"
            :max="scope.row.quantityMax"
            :min="0.01"
            :step="0.01"
            :precision="2"
            @change="computeIssue1(scope.row)"
            v-model="scope.row.quantityIssued"
            placeholder="请输入领料数量" />
          <span v-else>{{ scope.row.quantityIssued }}</span>
        </template>
      </el-table-column>

      <el-table-column label="单位（库存）" align="center" prop="storageUnit" fixed="right"/>
      <el-table-column label="领料数量（库存）" align="center" prop="storageUnitQuantity" width="120" fixed="right">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.updateStatus&&scope.row.enableMultiUnit === 'Y'"
            size="mini"
            style="width: 100px"
            :max="scope.row.quantityUnitMax"
            :min="0.01"
            :step="0.01"
            :precision="2"
            @change="computeIssue2(scope.row)"
            v-model="scope.row.storageUnitQuantity"
            placeholder="请输入领料数量" />
          <span v-else>{{ scope.row.storageUnitQuantity }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        v-if="isExecute"
        width="120px"
        class-name="small-padding fixed-width"
      fixed="right"
      >
       <template slot-scope="scope">
         <!--    <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-if="optType != 'view' && !scope.row.updateStatus"
              v-hasPermi="['mes:wm:outsourceissue:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="saveLine(scope.row)"
              v-if="optType != 'view' && scope.row.updateStatus"
              v-hasPermi="['mes:wm:outsourceissue:edit']"
            >保存</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"

            v-hasPermi="['mes:wm:outsourceissue:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <StockSelect
      ref="stockSelect"
      :itemCode="itemCode"
      :itemId="itemId"
      :issueValue="issueValue"
      :enableMultiUnit="enableMultiUnit"
      :storageUnitType="storageUnitType"
      :storageRatio="storageRatio"
      @onSelected="onStockSelected"
    />
  </div>
</template>

<script>
import { listOutsourceissueline, getOutsourceissueline, delOutsourceissueline, addOutsourceissueline, updateOutsourceissueline } from "@/api/mes/wm/outsourceissueline";
import StockSelect from "@/views/mes/wm/outsourceissue/stockSingleSelect.vue"
import Template from "@/views/print/printtemplate/list.vue";
import {getColumnsConfigKey} from "@/api/system/columnsconfig";
export default {
  name: "Outsourceissueline",
  components:{Template, StockSelect},
  props:{
    workorderId:null,
    optType: null,
    issueId: null,
    warehouseId: null,
    locationId: null,
    areaId: null,
    isExecute:false,
    bomId:null,
  },
  data() {
    return {
      itemId:null,
      itemCode:null,
      enableMultiUnit:null,
      storageUnitType:null,
      storageRatio:null,
      storageUnit:null,
      issueValue:0.00,
      columnsConfig:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 外协领料单行表格数据
      outsourceissuelineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        issueId: this.issueId,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityIssued: null,
        batchCode: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemId: [
          { required: true, message: "产品物料不能为空", trigger: "blur" }
        ],
        quantityIssued: [
          { required: true, message: "领料数量不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getItemBase();
  },
  watch:{
    outsourceissuelineList(newVal) {
        this.$emit('child-list-updated', newVal);
      }
  },
  methods: {
    computeIssue1(row){
      if(row.enableMultiUnit==='Y'){
        if(row.storageUnitType==='fixed'){

          if(row.storageRatio){
            row.storageUnitQuantity=row.quantityIssued/row.storageRatio;
          }
        }
      }
    },
    computeIssue2(row){
      if(row.enableMultiUnit==='Y'){
        if(row.storageUnitType==='fixed'){
          if(row.storageRatio){
            row.quantityIssued=row.storageUnitQuantity*row.storageRatio;
          }
        }
      }
    },
    getItemBase(){
      getColumnsConfigKey('MdItem_Base').then(res=>{
        this.columnsConfig = JSON.parse(res.data);
      })
    },
    /** 查询外协领料单行列表 */
    getList() {
      this.loading = true;
      listOutsourceissueline(this.queryParams).then(response => {

        this.outsourceissuelineList =   response.rows.map(item => {
          item.updateStatus=false;
          return item;
        })
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        lineId: null,
        issueId: this.issueId,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityIssued: null,
        batchCode: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lineId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.$refs.stockSelect.showFlag = true;
    },
    saveLine(row){
      if(row.quantityIssued > 0) {
        updateOutsourceissueline(row).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      row.updateStatus = true;
      //this.reset();
     // const lineId = row.lineId || this.ids
    /*  getOutsourceissueline(lineId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改外协发料单行";
      });*/
    },
    /** 提交按钮 */
    /*submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.lineId != null) {
            updateOutsourceissueline(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOutsourceissueline(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },*/
    /** 删除按钮操作 */
    handleDelete(row) {
      const lineIds = row.lineId || this.ids;
      this.$modal.confirm('是否确认删除"' + row.itemName + '"的数据项？').then(function() {
        return delOutsourceissueline(lineIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleSelectStock(){
      this.$refs.stockSelect.showFlag = true;
      //this.$refs.stockSelect.getList();
    },
    //物料选择弹出框
    onStockSelected(obj){
        if(obj != undefined && obj != null){
          this.form.materialStockId = obj.materialStockId;
          this.form.itemId = obj.itemId;
          this.form.itemCode = obj.itemCode;
          this.form.itemName = obj.itemName;
          this.form.specification = obj.specification;
          this.form.unitOfMeasure = obj.unitOfMeasure;
          this.form.batchCode = obj.batchCode;
          this.form.warehouseId = obj.warehouseId;
          this.form.warehouseCode = obj.warehouseCode;
          this.form.warehouseName = obj.warehouseName;
          this.form.locationId = obj.locationId;
          this.form.locationCode = obj.locationCode;
          this.form.locationName = obj.locationName;
          this.form.areaId = obj.areaId;
          this.form.areaCode = obj.areaCode;
          this.form.areaName = obj.areaName;
          this.form.quantityIssued = obj.quantityOutPrimary;
          this.form.enableMultiUnit=this.enableMultiUnit;
          this.form.storageUnitType=this.storageUnitType;
          this.form.storageRatio=this.storageRatio;
          this.form.storageUnit=this.storageUnit;
          this.form.storageUnitQuantity=obj.quantityOutWarehouse;
         this.form.issueId=this.issueId;
          addOutsourceissueline(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
    },
  }
};
</script>
